package com.jiayou.activity


import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.text.InputType
import android.view.View
import android.view.WindowManager
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import cn.hutool.extra.ssh.JschUtil
import cn.hutool.http.HttpRequest
import cn.hutool.json.JSONUtil
import com.jiayou.R
import com.jiayou.activity.adapter.User
import com.jiayou.activity.adapter.UserAdapter
import com.jiayou.client.ImClient
import com.jiayou.message.ChannelMessage
import com.jiayou.message.TextMessage
import com.jiayou.message.type.DataType
import com.jiayou.tool.AndroidTool
import com.jiayou.tool.SerializableTool
import com.qmuiteam.qmui.widget.dialog.QMUIDialog.EditTextDialogBuilder
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.chat_item.*
import kotlinx.android.synthetic.main.menu_item.*
import kotlinx.android.synthetic.main.tab_bar.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import java.lang.Exception
import java.time.LocalDateTime
import java.util.*
import java.util.concurrent.TimeUnit
import kotlin.collections.ArrayList
import kotlin.concurrent.thread


//192.168.43.216
class MainActivity : AppCompatActivity(), View.OnClickListener {
    companion object {
        lateinit var ID: String   //id
        lateinit var petname: String //昵称
        var gender: Int = 0 //性别
        lateinit var description: String //个人说明
        lateinit var img: String        //头像
        lateinit var client: ImClient
    }

    private val properties = Properties()
    lateinit var uri: String

    @RequiresApi(Build.VERSION_CODES.M)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        AndroidTool.fullScreen(this)


        properties.load(application.assets.open("im.properties"))
        uri = properties["im.uri"].toString() + ":" + properties["im.port"].toString()


        getIntentData()
        updateNichengAndTouxaing(this)


        tab1.setOnClickListener(this)
        tab2.setOnClickListener(this)
        tab3.setOnClickListener(this)
        function.setOnClickListener(this)
        view.setOnClickListener(this)
        tab1_img.setBackgroundResource(R.drawable.msg_active)
        about_im.setOnClickListener(this)
        userinfo.setOnClickListener(this)
        pengyouquan.setOnClickListener(this)


        try {
            //启动客户端netty
            thread {
                client = ImClient(
                    this,
                    ID,
                    properties["im.uri"].toString(),
                    properties["netty.port"].toString().toInt()
                )
                client.startClient()
            }
            //初始化好友列表
            initFrieds()
            //定时刷新好友列表
            cronGetFriends()
        } catch (e: Exception) {
            Toast.makeText(this, e.message, Toast.LENGTH_SHORT).show()
        }
    }


    private fun getIntentData() {
        ID = intent.getStringExtra("username").toString()
        petname = intent.getStringExtra("petname").toString()
        gender = intent.getIntExtra("gender", 0)
        description = intent.getStringExtra("description").toString()
        img = intent.getStringExtra("img").toString()
        nicheng.text = petname
        im_id.text = "IM号： $ID"
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onClick(p0: View) {
        when (p0.id) {
            R.id.tab1 -> {
                tab_title.text = "消息"
                //颜色重置
                tab1_text.setTextColor(Color.parseColor("#00CC00"))
                tab2_text.setTextColor(Color.parseColor("#808080"))
                tab3_text.setTextColor(Color.parseColor("#808080"))
                //图标重置
                tab1_img.setBackgroundResource(R.drawable.msg_active)
                tab2_img.setBackgroundResource(R.drawable.friend)
                tab3_img.setBackgroundResource(R.drawable.me)
                //page重置
                page1.visibility = View.VISIBLE
                page2.visibility = View.GONE
                page3.visibility = View.GONE

                //显示第三页被隐藏的view
                function.setBackgroundResource(R.drawable.function)
                view.visibility = View.VISIBLE
            }
            R.id.tab2 -> {
                tab_title.text = "联系人"
                //颜色重置
                tab1_text.setTextColor(Color.parseColor("#808080"))
                tab2_text.setTextColor(Color.parseColor("#00CC00"))
                tab3_text.setTextColor(Color.parseColor("#808080"))
                //图标重置
                tab1_img.setBackgroundResource(R.drawable.msg)
                tab2_img.setBackgroundResource(R.drawable.friend_active)
                tab3_img.setBackgroundResource(R.drawable.me)
                //page重置
                page1.visibility = View.GONE
                page2.visibility = View.VISIBLE
                page3.visibility = View.GONE

                //显示第三页被隐藏的view
                function.setBackgroundResource(R.drawable.function)
                view.visibility = View.VISIBLE
            }
            R.id.tab3 -> {
                tab_title.text = " "
                //颜色重置
                tab1_text.setTextColor(Color.parseColor("#808080"))
                tab2_text.setTextColor(Color.parseColor("#808080"))
                tab3_text.setTextColor(Color.parseColor("#00CC00"))
                //图标重置
                tab1_img.setBackgroundResource(R.drawable.msg)
                tab2_img.setBackgroundResource(R.drawable.friend)
                tab3_img.setBackgroundResource(R.drawable.me_active)
                //page重置
                page1.visibility = View.GONE
                page2.visibility = View.GONE
                page3.visibility = View.VISIBLE

//                function.setBackgroundResource(0)
                view.visibility = View.GONE
            }
            R.id.function -> {
                showEditTextDialog()
            }
            R.id.userinfo -> {
                startActivity(Intent(this, UserInfoActivity::class.java))
            }
            R.id.about_im -> {
                startActivity(Intent(this, AboutActivity::class.java))
            }
            R.id.pengyouquan -> {
                startActivity(Intent(this, MomentsActivity::class.java))
            }
        }
    }


    override fun onBackPressed() =
        startActivity(Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME))


    private fun showEditTextDialog() {
        val builder = EditTextDialogBuilder(this)
        builder.setTitle("添加好友")
            .setPlaceholder("请输入需要添加的好友ID")
            .setInputType(InputType.TYPE_CLASS_TEXT)
            .addAction(
                "取消"
            ) { dialog, index -> dialog.dismiss() }
            .addAction(
                "确定"
            ) { dialog, index ->
                val text: CharSequence? = builder.editText.text
                if (text != null && text.isNotEmpty()) {
                    if (text == ID) {
                        runBlocking {
                            withContext(Dispatchers.Main) {
                                Toast.makeText(
                                    this@MainActivity,
                                    "请不要添加自己，系统会bug",
                                    Toast.LENGTH_SHORT
                                ).show()
                                Unit
                            }
                        }
                        dialog.dismiss()
                        return@addAction
                    }
                    thread {
                        runBlocking {
                            val parse = JSONUtil.parseObj(
                                HttpRequest.post("http://${uri}/im/operation/getOperation")
                                    .form(
                                        mapOf(
                                            "id1" to ID,
                                            "id2" to text.toString(),
                                            "operation" to 1
                                        )
                                    )
                                    .header("auth", "73913da7-508b-4646-b8ae-ef6458f41153")
                                    .execute()
                                    .body()
                            )
                            dialog.dismiss()
                            withContext(Dispatchers.Main) {
                                Toast.makeText(
                                    this@MainActivity,
                                    parse["data"].toString(),
                                    Toast.LENGTH_SHORT
                                ).show()
                                Unit
                            }
                            initFrieds()
                        }
                    }
                } else {
                    Toast.makeText(this, "请输入ID", Toast.LENGTH_SHORT).show()
                }
            }
            .show()
    }

    private fun initFrieds() {
        thread {
            runBlocking {
                val parse = JSONUtil.parseObj(
                    HttpRequest.get("http://${uri}/im/relation/getRelation")
                        .form(
                            mapOf(
                                "id" to ID
                            )
                        )
                        .header("auth", "73913da7-508b-4646-b8ae-ef6458f41153")
                        .execute()
                        .body()
                )

                if (parse["code"].toString().toInt() == 200) {
                    val list = ArrayList<User>()
                    JSONUtil.parseArray(parse["data"]).forEach {
                        val obj = JSONUtil.parseObj(it)
                        list.add(
                            User(
                                obj["username"].toString(),
                                obj["petname"].toString(),
                                if (obj["gender"].toString().toInt() == 0) "女" else "男",
                                obj["description"].toString(),
                                obj["img"].toString()
                            )
                        )
                    }
                    withContext(Dispatchers.Main) {
                        friends.adapter = UserAdapter(this@MainActivity, list)
                        val manager = LinearLayoutManager(this@MainActivity)
                        manager.orientation = LinearLayoutManager.VERTICAL
                        friends.layoutManager = manager
                    }
                }
            }
        }
    }

    private fun cronGetFriends() {
        thread {
            while (true) {
                initFrieds()
                Thread.sleep(30000)
            }
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        nicheng.text = petname
    }


    private fun updateNichengAndTouxaing(activity: MainActivity) {
        thread {
            while (true) {
                runBlocking {
                    withContext(Dispatchers.Main) {
                        activity.nicheng.text = MainActivity.petname
                    }
                }
                Thread.sleep(5000)
            }
        }

        thread {
            while (true) {
                val bodyStream = HttpRequest.get("http://$uri/im/userinfo/getImgByName").form("img", img)
                    .header("auth", "73913da7-508b-4646-b8ae-ef6458f41153")
                    .execute()
                    .bodyStream()

                runBlocking {
                    withContext(Dispatchers.Main) {
                        imageView.setImageBitmap(BitmapFactory.decodeStream(bodyStream))
                    }
                }
                Thread.sleep(30000)
            }
        }
    }
}